﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;

namespace AdbService
{
    /// <summary>
    /// 优化的Logcat数据管理器
    /// </summary>
    public static class LogcatDataManager
    {
        // 使用并发集合替代原来的List和锁
        private static readonly ConcurrentDictionary<string, LogcatModel> _registerCache = new ConcurrentDictionary<string, LogcatModel>();
        private static readonly ConcurrentQueue<LogcatModel> _recentLogs = new ConcurrentQueue<LogcatModel>();

        // 全局变量：控制最大存储数量
        private static int _maxLogCount = 500;

        // 用于事件通知
        public static event Action<LogcatModel> OnRegisterDataUpdated;

        /// <summary>
        /// 设置或获取最大日志记录数量
        /// </summary>
        public static int MaxLogCount
        {
            get { return _maxLogCount; }
            set
            {
                if (value > 0)
                {
                    _maxLogCount = value;
                    Console.WriteLine($"[LogcatDataManager] 最大日志数量设置为: {_maxLogCount}");

                    // 清理超出限制的最近日志
                    TrimExcessRecentLogs();
                }
                else
                {
                    Console.WriteLine($"[LogcatDataManager WARNING] 无效的最大日志数量: {value}，必须大于0");
                }
            }
        }

        /// <summary>
        /// 从日志行中解析寄存器信息并自动存储
        /// </summary>
        /// <param name="logLine">日志行</param>
        /// <returns>解析是否成功</returns>
        public static bool ParseAndStoreRegisterLog(string logLine)
        {
            if (string.IsNullOrEmpty(logLine))
                return false;

            // 优化后的正则表达式，更精确地匹配日志格式
            Match match = Regex.Match(
                logLine,
                @"(ISP|Sensor|Reg)(Read|Write)\s+.*?addr=(0x[0-9a-fA-F]+)\s+val=(0x[0-9a-fA-F]+)\s+id=([0-9]+)\s+online=([0-9]+)");

            if (!match.Success)
                return false;

            try
            {
                string module = match.Groups[1].Value;
                string operation = match.Groups[2].Value;
                string regAddr = match.Groups[3].Value;
                string value = match.Groups[4].Value;
                string id = match.Groups[5].Value;
                bool isRead = string.Equals(operation, "read", StringComparison.OrdinalIgnoreCase);
                bool online = match.Groups[6].Value == "1";

                // 创建LogcatModel对象
                var logcatModel = new LogcatModel
                {
                    Date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"),
                    Operation = isRead ? "Read" : "Write",
                    RWText = module,
                    RegAddr = regAddr,
                    Values = value,
                    Online = online
                };

                // 存储到数据管理器
                AddData(logcatModel);

                //Console.WriteLine($"[LogcatDataManager] 成功解析并存储日志: {module}{operation}, 地址: {regAddr}, 值: {value}, 在线: {online}");
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[LogcatDataManager ERROR] 解析日志失败: {ex.Message}, 日志行: {logLine}");
                return false;
            }
        }

        /// <summary>
        /// 添加单个Logcat数据
        /// </summary>
        /// <param name="model">Logcat数据模型</param>
        public static void AddData(LogcatModel model)
        {
            if (model == null || string.IsNullOrWhiteSpace(model.RegAddr))
                return;

            try
            {
                // 格式化寄存器地址
                string formattedAddr = FormatRegisterAddress(model.RegAddr);

                // 更新缓存 - 总是使用最新的值
                _registerCache.AddOrUpdate(formattedAddr, model, (key, oldValue) => model);

                // 添加到最近日志队列
                _recentLogs.Enqueue(model);

                // 维护队列大小
                TrimExcessRecentLogs();

                // 触发数据更新事件
                OnRegisterDataUpdated?.Invoke(model);

                //Console.WriteLine($"[LogcatDataManager] 已添加数据，寄存器: {model.RegAddr}，操作: {model.Operation}，缓存总数: {_registerCache.Count}，队列总数: {_recentLogs.Count}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[LogcatDataManager ERROR] 添加数据失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 根据寄存器地址查找数据，支持读写操作判断
        /// </summary>
        /// <param name="regAddr">寄存器地址</param>
        /// <param name="operation">操作类型：Read、Write 或 Any（默认）</param>
        /// <param name="timeoutMs">超时时间（毫秒），默认为0表示不等待</param>
        /// <returns>匹配的数据或默认值"0"</returns>
        public static async Task<LogcatModel> FindByRegisterAddressSync(string regAddr, string operation = "Any", int timeoutMs = 10000)
        {
            if (string.IsNullOrWhiteSpace(regAddr))
            {
                Console.WriteLine($"[LogcatDataManager] 寄存器地址为空，返回默认值");
                return new LogcatModel();
            }

            try
            {
                string formattedAddr = FormatRegisterAddress(regAddr);
                operation = operation?.ToLower() ?? "any";

                // 首先尝试从缓存中直接获取
                if (_registerCache.TryGetValue(formattedAddr, out var cachedResult) &&
                    !string.IsNullOrEmpty(cachedResult.Values))
                {
                    // 检查操作类型是否匹配
                    if (IsOperationMatch(cachedResult.Operation, operation))
                    {
                        Console.WriteLine($"[LogcatDataManager] 从缓存找到寄存器 '{regAddr}'，操作: {cachedResult.Operation}，值: {cachedResult.Values}");
                        return cachedResult;
                    }
                    //else
                    //{
                    //    Console.WriteLine($"[LogcatDataManager] 缓存中找到寄存器 '{regAddr}'，但操作类型不匹配。期望: {operation}，实际: {cachedResult.Operation}");
                    //}
                }

                // 如果缓存中没有且需要等待，则等待数据到达
                if (timeoutMs > 0)
                {
                    return await WaitForRegisterDataAsync(formattedAddr, operation, timeoutMs);
                }

                Console.WriteLine($"[LogcatDataManager] 寄存器 '{regAddr}' 未找到匹配的操作类型 '{operation}'，返回默认值");
                return new LogcatModel();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[LogcatDataManager ERROR] 查找寄存器地址 '{regAddr}' 时发生异常: {ex.Message}");
                return new LogcatModel();
            }
        }


        /// <summary>
        /// 等待特定寄存器数据到达，支持操作类型过滤
        /// </summary>
        private static async Task<LogcatModel> WaitForRegisterDataAsync(string formattedAddr, string operation, int timeoutMs)
        {
            var startTime = DateTime.Now;
            var checkInterval = Math.Min(50, timeoutMs / 10); // 动态调整检查间隔

            Console.WriteLine($"[LogcatDataManager] 开始等待寄存器 '{formattedAddr}'，操作类型: {operation}，超时: {timeoutMs}ms");

            while ((DateTime.Now - startTime).TotalMilliseconds < timeoutMs)
            {
                // 检查缓存
                if (_registerCache.TryGetValue(formattedAddr, out var result) &&
                    !string.IsNullOrEmpty(result.Values) &&
                    IsOperationMatch(result.Operation, operation))
                {
                    var elapsedMs = (DateTime.Now - startTime).TotalMilliseconds;
                    Console.WriteLine($"[LogcatDataManager] 等待 {elapsedMs:F0}ms 后找到寄存器 '{formattedAddr}'，操作: {result.Operation}，值: {result.Values}");
                    return result;
                }

                // 检查最近日志（处理缓存未及时更新的情况）
                var recentFound = FindInRecentLogs(formattedAddr, operation);
                if (recentFound != null)
                {
                    var elapsedMs = (DateTime.Now - startTime).TotalMilliseconds;
                    Console.WriteLine($"[LogcatDataManager] 从最近日志找到寄存器 '{formattedAddr}'，操作: {recentFound.Operation}，值: {recentFound.Values}");
                    return recentFound;
                }

                // 动态调整等待时间
                var remainingTime = timeoutMs - (int)(DateTime.Now - startTime).TotalMilliseconds;
                if (remainingTime <= 0) break;

                var waitTime = Math.Min(checkInterval, remainingTime);
                await Task.Delay(waitTime);
            }

            Console.WriteLine($"[LogcatDataManager] 等待超时，寄存器 '{formattedAddr}' 未找到匹配的操作类型 '{operation}'");
            return new LogcatModel();
        }

        /// <summary>
        /// 在最近日志中查找，支持操作类型过滤
        /// </summary>
        private static LogcatModel FindInRecentLogs(string formattedAddr, string operation)
        {
            // 从最新的日志开始查找
            foreach (var log in _recentLogs.Reverse())
            {
                if (log != null &&
                    !string.IsNullOrWhiteSpace(log.RegAddr) &&
                    FormatRegisterAddress(log.RegAddr) == formattedAddr &&
                    !string.IsNullOrEmpty(log.Values) &&
                    IsOperationMatch(log.Operation, operation))
                {
                    return log;
                }

                // 限制检查数量，避免性能问题
                if (_recentLogs.Count > 1000)
                    break;
            }
            return null;
        }
        /// <summary>
        /// 检查操作类型是否匹配
        /// </summary>
        private static bool IsOperationMatch(string actualOperation, string expectedOperation)
        {
            if (string.IsNullOrEmpty(expectedOperation) || expectedOperation.ToLower() == "any")
                return true;

            return string.Equals(actualOperation?.Trim(), expectedOperation?.Trim(), StringComparison.OrdinalIgnoreCase);
        }
        /// <summary>
        /// 格式化寄存器地址
        /// </summary>
        private static string FormatRegisterAddress(string regAddr)
        {
            string formatted = regAddr.Trim();
            if (!formatted.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
            {
                formatted = "0x" + formatted;
            }
            return formatted.ToLowerInvariant();
        }

        /// <summary>
        /// 同步版本的查找方法，支持读写操作判断
        /// </summary>
        public static LogcatModel FindByRegisterAddress(string regAddr, string operation = "Any", int timeoutMs = 5000)
        {
            return FindByRegisterAddressSync(regAddr, operation, timeoutMs).GetAwaiter().GetResult();
        }

        /// <summary>
        /// 清理超出最大限制的最近日志
        /// </summary>
        private static void TrimExcessRecentLogs()
        {
            while (_recentLogs.Count > _maxLogCount && _recentLogs.TryDequeue(out _))
            {
                // 持续出队直到满足大小限制
            }
        }

        /// <summary>
        /// 清理所有数据
        /// </summary>
        public static void Clear()
        {
            _registerCache.Clear();
            while (_recentLogs.TryDequeue(out _)) { }
            Console.WriteLine("[LogcatDataManager] 所有数据已清理");
        }

        /// <summary>
        /// 清空指定寄存器的缓存
        /// </summary>
        public static void ClearRegisterCache(string regAddr)
        {
            if (string.IsNullOrWhiteSpace(regAddr))
                return;

            try
            {
                string formattedAddr = FormatRegisterAddress(regAddr);

                // 从缓存中移除
                _registerCache.TryRemove(formattedAddr, out _);

                Console.WriteLine($"[LogcatDataManager] 已清空寄存器 {formattedAddr} 的缓存");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[LogcatDataManager ERROR] 清空寄存器缓存失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取所有缓存的寄存器地址（用于调试）
        /// </summary>
        public static List<string> GetCachedRegisterAddresses()
        {
            return _registerCache.Keys.ToList();
        }



    }
}